package it.trekker.prefetch.ejb;

import it.trekker.dao.Excursion;
import it.trekker.dao.IExcursionDAO;
import it.trekker.dao.User;
import it.trekker.prefetch.ExcursionsCache;
import it.trekker.prefetch.ICacheLoader;

import java.util.List;
import javax.annotation.Resource;
import javax.ejb.Asynchronous;
import javax.ejb.EJB;
import javax.ejb.Local;
import javax.ejb.SessionContext;
import javax.ejb.Stateless;
import org.apache.log4j.Logger;


/**
 * Goal of that class: avoid problem with asynchronous method in a stateful session bean.
 * In JBoss 7.1.1 asynchronous method in a stateful session bean doesn't works asynchronously.
 * (See ExcursionDAOWithPrefetch class)
 */


//@Interceptors({CacheLoaderLogger.class})
@Stateless
@Local(ICacheLoader.class)
@Asynchronous
public class CacheLoader implements ICacheLoader {

	private static final Logger logger = Logger.getLogger(CacheLoader.class.getCanonicalName());

	@Resource
	SessionContext ctx;

	//	@EJB(lookup="ejb:TrekkerServer/TrekkerServer.jar/EJB3ExcursionDAO!it.trekker.dao.IExcursionDAO")
	@EJB
	IExcursionDAO excursionDAO;


	public void loadCacheWithCloseExcursions(ExcursionsCache cache, Excursion excursion, double radius) {

		if(excursion != null) {
			cache.addExcursion(excursion);
			List<Excursion> closeExcursions = excursionDAO.findCloseExcursions(excursion, radius);
			if(closeExcursions != null) {
				for(Excursion exc : closeExcursions) {
					cache.addExcursion(exc);
				}
			}
			//			ctx.getBusinessObject(ICacheLoader.class).loadCacheWithGivenExcursions(cache, closeExcursions, excursion.getStartPoint());
			//			loadCacheWithGivenExcursions(cache, closeExcursions);
		}

		//		try {
		//			Thread.sleep(4000);
		//		} catch (InterruptedException e) {
		//			e.printStackTrace();
		//		}

//		cache.logAllCache();
	}



	public void loadCacheWithUserExcursions(ExcursionsCache cache, User user) {

		if(user != null) {
			List<Excursion> closeExcursions = excursionDAO.findExcursionsByUser(user);
			if(closeExcursions != null) {
				for(Excursion exc : closeExcursions) {
					cache.addExcursion(exc);
				}
			}
		}

	}



	public void loadCacheWithGivenExcursions(ExcursionsCache cache, List<Excursion> excursionList) {

		if(excursionList != null) {
			for(Excursion excursion : excursionList) {
				cache.addExcursion(excursion);
			}
		}

	}
}
